/**
 * 店铺授权弹框
 */

import React, { useState, useEffect, useMemo } from "react";
import { CommonModal } from "@/views/components/CommonModal";
import BuyConfirm from "./BuyConfirm";
import { Base64 } from "js-base64";
import { message, Button } from "antd";
import { find } from "lodash";
import { getCurrentUser } from "@/utils/authority";
import styles from "./index.module.less";
import useSettingStore from "@/stores/setting";
import AddJingdongStore from "./AddJingdongStore";
import AddOfflineStore from "./AddOfflineStore";
import { queryEcPlatformConfigList } from "../../service";
import CommonLoading from "@/components/CommonLoading";
import SubTitle from "@/views/components/SubTitle";
import { checkAccount } from "@/services/common";
import AddVideoStore from "./AddVideoStore";

let isJumpLogin;

const AuthorizeStore = ({ visible, shopPlatform, handleCancel }) => {
	const title = useSettingStore(state => state.title);

	const [selectItem, setSelectItem] = useState({}); //当前选中的平台
	const [visible1, setVisible] = useState(1);
	const [storeList, setStoreList] = useState([]); //授权店铺列表
	const [loading, setLoading] = useState(false);
	const [accountMsg, setAccountMsg] = useState({});
	const [mouseId, setMouseId] = useState(0); //鼠标移入哪个平台的id

	useEffect(() => {
		isJumpLogin = sessionStorage.getItem("mall_authorize_pdd");
		sessionStorage.setItem("mall_authorize_pdd", "");
		getEcPlatformConfigList();
		queryAccount();
	}, []);

	//获取用户信息
	const queryAccount = async () => {
		setLoading(true);
		const { data = {}, success } = await checkAccount();
		if (success) {
			setAccountMsg(data);
		}
		setLoading(false);
	};

	//获取店铺数据
	const getEcPlatformConfigList = async () => {
		setLoading(true);
		const { data = [], success } = await queryEcPlatformConfigList({ orderBy: 1, status: 10 });
		if (success) {
			setStoreList(data);
		}
		setLoading(false);
	};

	const baseData = [
		//天猫
		{
			platform: 18,
			src: "https://imgniu.zhaojiafang.com/front-web/ERP/tianmao.png",
			name: "天猫",
			path: `https://oauth.taobao.com/authorize?response_type=code&client_id=23416550&redirect_uri=http://tb-api.zhaojiafang.com/TopSdk.php&state=${AUTHORIZE_URL}/taobao/callback-callback-`
		},
		//京东
		{
			platform: 1,
			src: "https://imgniu.zhaojiafang.com/front-web/ERP/jd.png",
			name: "京东",
			path: `https://auth.360buy.com/oauth/authorize?response_type=code&client_id=7400F31DF539216DBDA2E06BD5E91C57&redirect_uri=http://threegateway.zhaojiafang.com/jd/callback&state=`
		},

		//抖音
		{
			platform: 15,
			src: "https://imgniu.zhaojiafang.com/front-web/ERP/dy.png",
			name: "抖音",
			path: `https://fuwu.jinritemai.com/authorize?service_id=1965&state=`
		},

		//京东云仓
		{
			platform: 19,
			src: "https://imgniu.zhaojiafang.com/front-web/ERP/jdyc.png",
			name: "京东云仓",
			path: `https://oauth.jdl.cn/oauth/authorize?client_id=3d9625d4bc294e6db002351d6fcc6d86&redirect_uri=http://threegateway.zhaojiafang.com/jdLogistics/callback&response_type=code&state=`
		},

		//快手
		{
			platform: 12,
			src: "https://imgniu.zhaojiafang.com/front-web/ERP/ks.png",
			name: "快手",
			path: `https://open.kwaixiaodian.com/oauth/authorize?appId=ks661466197236322196&redirect_uri=http://threegateway.zhaojiafang.com/ks/callback&scope=merchant_refund,merchant_item,merchant_order,user_info,merchant_user,merchant_logistics&response_type=code&state=`
		},

		//线下店铺
		{
			platform: 0,
			src: "https://imgniu.zhaojiafang.com/front-web/ERP/xianxia.png",
			name: "线下店铺"
		},

		//拼多多，需要支持双应用授权，new_path是商城跳转过来携带授权参数时使用
		{
			platform: 9,
			src: "https://imgniu.zhaojiafang.com/front-web/ERP/pdd2.png",
			name: "拼多多",
			path: `https://mms.pinduoduo.com/open.html?response_type=code&client_id=fac6930771f14534b31d48f15f7d8a4a&redirect_uri=http://threegateway.zhaojiafang.com/pdd/newKey/oneClickLogin&state=`
		}
	];

	const data = useMemo(() => {
		if (shopPlatform == "qimen") {
			return [
				//淘宝易发货
				{
					id: 26,
					src: "https://imgniu.zhaojiafang.com/front-web/ERP/tb.png",
					name: "淘宝(易发货)",
					path: `https://oauth.taobao.com/authorize?response_type=code&client_id=23416550&redirect_uri=http://tb-api.zhaojiafang.com/TopSdk.php&state=${AUTHORIZE_URL}/taobao/callback-callback-`
				}
			];
		} else {
			return [
				//淘宝
				{
					platform: 8,
					src: "https://imgniu.zhaojiafang.com/front-web/ERP/tb.png",
					name: "淘宝",
					path: `https://oauth.taobao.com/authorize?response_type=code&client_id=23416550&redirect_uri=http://tb-api.zhaojiafang.com/TopSdk.php&state=${AUTHORIZE_URL}/taobao/callback-callback-`
				},
				...baseData
			];
		}
	}, [shopPlatform]);

	//点击确定
	function handleOk() {
		handleCancel();
		setMouseId(0);
		if (selectItem.platform) {
			if (selectItem.platform == 25) {
				setVisible(25)
			} else if(selectItem.platform == 19) {
				setVisible(6);
			} else {
				setVisible(2);
			}
		} else {
			if (selectItem.platform == 0) {
				//线下店铺
				setVisible(3);
			} else {
				message.warning("请选择平台！");
			}
		}
	}

	//开始授权前信息处理
	const handleAuthorize = (val = {}) => {
		if ([8, 18].includes(selectItem.platform)) {
			//淘宝
			const url = window.location.href;
			const obj = {
				url,
				userName: getCurrentUser().account,
				uuid: getCurrentUser().uuid,
				userId: accountMsg?.id + "",
				...val
			};
			let path = find(data, ["platform", selectItem.platform]).path;
			if (selectItem.platform == "26" || (selectItem.platform == "1" && title == "易发货")) {
				//淘宝商品在子域名为wmso
				obj.josUrl = `http://${AUTHORIZE_URL}`;
				path = `https://oauth.taobao.com/authorize?response_type=code&client_id=31991507&redirect_uri=http://threegateway.zhaojiafang.com/taobao/wms/callback&view=web&state=`;
			}
			const src = `${path}${encodeURIComponent(Base64.encode(JSON.stringify(obj)))}`;
			window.location.href = src;
		} else if ([1, 12, 15].includes(selectItem.platform)) {
			//京东/快手/抖音
			const url = window.location.href;
			const obj = JSON.stringify({
				url,
				userName: getCurrentUser().account,
				uuid: getCurrentUser().uuid,
				josUrl: `http://${AUTHORIZE_URL}`,
				userId: accountMsg?.id + "",
				...val
			});
			const path = find(data, ["platform", selectItem.platform]).path;
			const src = `${path}${Base64.encode(encodeURIComponent(obj))}`;
			window.location.href = src;
		} else if (selectItem.platform == 19) {
			//京东云仓
			const url = window.location.href;
			const obj = JSON.stringify({
				url,
				userName: getCurrentUser().account,
				uuid: getCurrentUser().uuid,
				josUrl: `http://${AUTHORIZE_URL}`,
				userId: accountMsg?.id + "",
				...val,
				spdFlag: 1
			});
			const path = find(data, ["platform", selectItem.platform]).path;
			const src = `${path}${encodeURIComponent(encodeURIComponent(Base64.encode(obj)))}`;
			window.location.href = src;
		} else if (selectItem.platform == 9) {
			//拼多多
			const url = window.location.href;
			const pddObj = {
				url,
				userName: getCurrentUser().account,
				uuid: getCurrentUser().uuid,
				josUrl: `http://${AUTHORIZE_URL}`,
				pddSource: 1,
				userId: accountMsg?.id + "",
				...val
			};
			// 从商城过来的授权pdd的参数有区别，跟京东平台的参数类似，这里通过跳转过来设置的session做区分，进行参数兼容
			// if (isJumpLogin) {
			//   pddObj.josUrl = `http://${AUTHORIZE_URL}`;
			// }
			const obj = JSON.stringify(pddObj);
			const path = find(data, ["platform", selectItem.platform]).path;
			const src = `${path}${Base64.encode(encodeURIComponent(obj))}`;
			window.location.href = src;
		}
	};

	//应用服务购买确认框以及订单去往选项
	const BuyConfirmProps = {
		shopPlatform,
		selectItem,
		isJumpLogin,
		visible: visible1 == 2,
		handleOk(val) {
			handleAuthorize(val);
		},
		handleCancel() {
			setVisible(1);
		}
	};

	//线下店铺弹框
	const AddOfflineStoreProps = {
		visible: visible1 == 3,
		handleVisible() {
			setVisible(1);
		}
	};

	//京东云仓
	const AddJingdongStoreProps = {
		visible: visible1 == 6,
		handleOk(val) {
			handleAuthorize(val);
		},
		handleVisible() {
			setVisible(1);
		}
	};

	const AddVideoStoreProps = {
		visible: visible1 == 25,
		handleVisible() {
			setVisible(1);
		}
	}

	const onCancel = () => {
		handleCancel();
		setVisible(1);
		setMouseId(0);
		setSelectItem({});
	};

	return (
		<>
			<CommonModal
				title={{ title: `店铺设置` }}
				visible={visible}
				onCancel={onCancel}
				width="600px"
				footer={[
					<Button className={styles.closeBtn} key="back" onClick={onCancel}>
						取消
					</Button>,
					<Button className={styles.okBtn} key="save" type="primary" onClick={handleOk}>
						确认
					</Button>
				]}
			>
				<div>
					<SubTitle title={"选择平台"} as="s2" symbol />
					<div className={styles.wrap}>
						{storeList.map(item => {
							return (
								<div key={item.id} className={styles.contentBox} onClick={() => setSelectItem(item)}>
									<div
										onMouseMove={e => {
											setMouseId(item.id);
										}}
										onMouseLeave={() => {
											setMouseId(0);
										}}
										className={styles.contentImg}
									>
										<img src={item.image} />
										{selectItem.id == item.id || mouseId == item.id ? (
											<div className={styles.textBg}>{item?.erpPlatformName}</div>
										) : (
											""
										)}
									</div>
								</div>
							);
						})}
					</div>
				</div>
			</CommonModal>
			<BuyConfirm {...BuyConfirmProps} />
			<AddJingdongStore {...AddJingdongStoreProps} />
			<AddOfflineStore {...AddOfflineStoreProps} />
			<AddVideoStore {...AddVideoStoreProps} />
			<CommonLoading loading={loading} />
		</>
	);
};

export default AuthorizeStore;
